package edu.gatech.cc.CFAWaffleFriesWheresMyStuff.gui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListAdapter;
import android.widget.TextView;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.R;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore.UserDoesNotExistException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.DatastoreFactory;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Item;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.ItemManager;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.User;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager;

/**
 * Displays a list of items.
 * @author Matthew Barulic
 *
 */
public class ItemListActivity extends ListActivity {

	private User _loggedInUser;
	private String _filterUser, _filterType, _filterCategory, _filterLocation, _filterName;
	private Long _filterDate;
	private Boolean _filterOpenClosed;
	private boolean _shouldShowMenu;
	private List<Item> _items;
	private ItemManager _itemManager;
	private UserManager _userManager;
	private Bundle _intentExtras;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_item_list);
		_intentExtras = getIntent().getExtras();
		
		((TextView)findViewById(R.id.itemListHeader)).setText(_intentExtras.getString("title"));
		
		Datastore db = DatastoreFactory.getDatastore(getApplicationContext());
		_itemManager = new ItemManager(db);
		_userManager = new UserManager(db);
		
		resetFiltersToCreationValues();
		
		SharedPreferences prefs = getSharedPreferences("itemListPrefs", MODE_PRIVATE);
		Set<String> runBefore = prefs.getStringSet("runBefore", new HashSet<String>());
		if(!runBefore.contains(_loggedInUser.getUsername()))
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Hi there!");
			builder.setMessage("You can filter your item list by pressing the menu button on your Android device!");
			builder.setCancelable(false);
			builder.setNeutralButton("OK", null);
			builder.create().show();
			
			SharedPreferences.Editor prefsEditor = prefs.edit();
			runBefore.add(_loggedInUser.getUsername());
			prefsEditor.putStringSet("runBefore", runBefore);
			prefsEditor.commit();
		}
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		if(_shouldShowMenu)
			getMenuInflater().inflate(R.menu.activity_item_list, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.sort_category:
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Choose A Category");
			builder.setItems(R.array.item_categories, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					_filterCategory = getResources().getStringArray(R.array.item_categories)[which];
					updateList();
				}
			});
			builder.create().show();
			return true;
		}
		
		case R.id.sort_type:
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Choose A Type");
			builder.setItems(R.array.item_types, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					_filterType = getResources().getStringArray(R.array.item_types)[which].replaceAll("\\s", "");
					updateList();
				}
			});
			builder.create().show();
			return true;
		}
			
		case R.id.sort_status:
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Choose A Category");
			builder.setItems(new String[] {"Open","Closed"}, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					_filterOpenClosed = which == 0;
					updateList();
				}
			});
			builder.create().show();
			return true;
		}
			
		case R.id.sort_date:
		{
			OnDateSetListener listener = new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					Calendar selected = new GregorianCalendar(year, monthOfYear, dayOfMonth);
					_filterDate = selected.getTimeInMillis() / 1000;
					updateList();
				}
			};
			Calendar today = Calendar.getInstance();
			DatePickerDialog dialog = new DatePickerDialog(this, listener, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
			dialog.show();
			return true;
		}
		
		case R.id.show_all_items:
		{
			resetFiltersToCreationValues();
			return true;
		}
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * Reverts all filter values to those passed into the intent when this activity was launched.
	 */
	protected void resetFiltersToCreationValues() {
		String username = _intentExtras.getString("loggedIn", null);
		if(username != null)
		{
			try {
				_loggedInUser = _userManager.getUser(username);
			} catch (UserDoesNotExistException e) {
				//This should never happen.
				e.printStackTrace();
			}
		}
		
		_filterUser = _intentExtras.getString("user", null);
		_filterType = _intentExtras.getString("type", null);
		_filterCategory = _intentExtras.getString("category", null);
		_filterLocation = _intentExtras.getString("location", null);
		String date = _intentExtras.getString("date", null);
		_filterDate = date != null ? Long.parseLong(date) : null;
		_filterName = _intentExtras.getString("itemName", null);
		String OCFilter = _intentExtras.getString("openClosed", null);
		if(OCFilter != null)
		{
			if(OCFilter.equals("Open"))
			{
				_filterOpenClosed = true;
			} else {
				_filterOpenClosed = false;
			}
		} else {
			_filterOpenClosed = null;
		}
		_shouldShowMenu = _intentExtras.getBoolean("enableMenu", true);
		
		updateList();
	}
	
	/**
	 * Reruns the filter defined in the private _filter____ variables.
	 */
	protected void updateList() {
		_items = _itemManager.getFilteredItems(_filterType, _filterOpenClosed, _filterCategory, _filterName, _filterDate, _filterLocation, _filterUser);
		setListAdapter(createAdapter());
	}

	/**
     * Creates and returns a list adapter for the current list activity
     * @return
     */
	protected ListAdapter createAdapter() {
		
		String[] values = new String[_items.size()];
		
		for(int i = 0; i < _items.size(); i++)
		{
			values[i] = _items.get(i).getName();
		}
		
		return new ItemListAdapter(this, R.layout.item_list_row, _items);
	}
	
	private class ItemListAdapter extends ArrayAdapter<Item> {
		private List<Item> items;
		
		public ItemListAdapter(Context context, int textViewResourceId, List<Item> items)
		{
			super(context, textViewResourceId, items);
			this.items = items;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.item_list_row, null);
            }
            Item item = items.get(position);
            if (item != null) {
                    TextView tt = (TextView) v.findViewById(R.id.itemlist_row_name);
                    TextView bt = (TextView) v.findViewById(R.id.itemlist_row_summary);
                    
                    if (tt != null) {
                          tt.setText(item.getName());
                    }
                    if(bt != null){
                          bt.setText(item.getDescription());
                    }
            }
            return v;
		}
	}
}
